package com.wb3.meta.common.utils;

import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class ConcurrentHttpClient {

    private static CloseableHttpClient httpClient;

    static {
        // 创建线程安全的 CloseableHttpClient
        httpClient = HttpClientBuilder.create()
                .setDefaultRequestConfig(RequestConfig.custom()
                        .setConnectTimeout(35000)
                        .setConnectionRequestTimeout(35000)
                        .setSocketTimeout(60000)
                        .build())
                .build();
    }

    public static Map<String, String> doPostJson(String url, Map<String, String> headers, String jsonStr) {
        Map<String, String> result = new ConcurrentHashMap<>();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Content-Type", "application/json");
        headers.forEach(httpPost::setHeader);

        try {
            httpPost.setEntity(new StringEntity(jsonStr, "UTF-8"));

            // 执行请求
            try (CloseableHttpResponse httpResponse = httpClient.execute(httpPost)) {
                // 处理响应
                result.put("code", String.valueOf(httpResponse.getStatusLine().getStatusCode()));
                result.put("result", EntityUtils.toString(httpResponse.getEntity()));
                return result;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    public static void main(String[] args) {
        // 示例调用
        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", "Bearer yourToken");
        String jsonStr = "{\"key\":\"value\"}";
        Map<String, String> response = doPostJson("https://example.com/api", headers, jsonStr);
        System.out.println(response);
    }
}

